/*
*
* 版权所有 Copyleft(c) 2005
* 刘炯个人工作室 Sharp-Mark Personal Studio
*
* 允许自由使用，复制，修改，传播和贩卖此源程序及其文档，而不必支付任何费用。
* 以上的版权信息必须出现在每一份复制品中。同时这份版权信息和许可声明
* 也必须出现在支持文档中。刘炯个人工作室不对此软件适于那种具体
* 用途做出任何阐述。此代码只作为代码本身提供对其品质不做任何保证。
*
*/

#include "stdafx.h"
#include "Polygon.h"

CEdge::CEdge(POINT p1, POINT p2)
{
	*this = CEdge(p1.x, p1.y, p2.x, p2.y);
}

CEdge::CEdge(int x1, int y1, int x2, int y2) : X1(x1), Y1(y1), X2(x2), Y2(y2)
{
	if(0 == y1 - y2)
	{
		dx = 0.0f;
	}
	else
	{
		dx = float(x2 - x1) / float(y2 - y1);
	}

	if(y1 >= y2)
	{
		yMax = y1; xMax = x1;
		yMin = y2; xMin = x2;
	}
	else
	{
		yMax = y2; xMax = x2;
		yMin = y1; xMin = x1;
	}

	//if (x1 >= x2)
	//{
	//	xMax = x1;
	//	xMin = x2;
	//}
	//else
	//{
	//	xMax = x2;
	//	xMin = x1;
	//}
}

CPolygon::CPolygon(CEdge* edges = 0, int num = 0) : Edges(edges), Num(num){}

CEdgeNode::CEdgeNode(){}

CNewEdgeTable::CNewEdgeTable(int nodesNumber) : _nodesNumber(nodesNumber)
{
	Links = vector< list <CEdgeNode> *>(nodesNumber);

	for(vector< list<CEdgeNode> * >::iterator lp = Links.begin(); lp != Links.end(); lp++)
	{
		(*lp) = new list<CEdgeNode>;
	}
}

CNewEdgeTable::~CNewEdgeTable()
{
	for(vector< list<CEdgeNode> * >::iterator lp = Links.begin(); lp != Links.end();)
	{
		vector< list< CEdgeNode > * >::iterator delp = lp;
		lp++;
		delete (*delp);
	}
}
CNewEdgeTable::CNewEdgeTable(){}

CActiveEdgeTable::CActiveEdgeTable(){}

void CActiveEdgeTable::InsertNodes(list<CEdgeNode> * top)
{
	for (list<CEdgeNode>::iterator p = top->begin(); p != top->end(); ++p)
	{
		Link.push_back(*p);
		Link.sort(CompareEdge());
	}
}

//CEdgeNode CEdgeNode::operator-(const CEdgeNode& rhs) const
//{
//	return CEdgeNode(this->X - rhs.X, 0, 0);
//}
//CEdgeNode CEdgeNode::operator+(const CEdgeNode& rhs) const
//{
//	return CEdgeNode(this->X - rhs.X, 0, 0);
//}
//bool operator==(const CEdgeNode& lhs, const CEdgeNode& rhs)
//{
//	return (lhs.X == rhs.X);
//}
//bool operator<(const CEdgeNode& lhs, const CEdgeNode& rhs)
//{
//	return (lhs.X < rhs.X);
//}
//bool operator>(const CEdgeNode& lhs, const CEdgeNode& rhs)
//{
//	return (lhs.X > rhs.X);
//}

int CPolygon::GetEdgePointY(int x, int y, float dx)
{
	float edx;
	for(int i = 0; i < Num; i++)
	{
		edx = float(Edges[i].X1 - Edges[i].X2) / float(Edges[i].Y1 - Edges[i].Y2);
		if(dx == edx)
		{
			if(Edges[i].X1 == x && Edges[i].Y1 == y)
				return Edges[i].Y2;
			if(Edges[i].X2 == x && Edges[i].Y2 == y)
				return Edges[i].Y1;
		}
	}

	return -1;
}

int CPolygon::GetEdgePointX(int x, int y, float dx)
{
	float edx;
	for(int i = 0; i < Num; i++)
	{
		edx = float(Edges[i].X1 - Edges[i].X2) / float(Edges[i].Y1 - Edges[i].Y2);
		if(dx == edx)
		{
			if(Edges[i].X1 == x && Edges[i].Y1 == y)
				return Edges[i].X2;
			if(Edges[i].X2 == x && Edges[i].Y2 == y)
				return Edges[i].X1;
		}
	}

	return -1;
}